<template>

    <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" icon="InfoFilled" icon-color="#626AEF"
        title="你确定要刷新吗" @confirm="onRefresh" >
        <template #reference>
            <el-button icon="Refresh" circle />
        </template>
    </el-popconfirm>

    <div class="show" v-if="opsType === ARTICLE_OPS_TYPE.SHOW">
        <h4>{{ article.stem }}</h4>
        <p v-html="article.content"></p>
    </div>

    <el-form label-width="55px" v-else>
        <el-form-item label="标题">
            <el-input placeholder="请输入文字标题" v-model="article.stem" />
        </el-form-item>
        <el-form-item label="内容">
            <QuillEditor :key="editorKey" theme="snow" toolbar="full" v-model:content="article.content"
                contentType="html" placeholder="请输入文章内容" />
        </el-form-item>
        <el-form-item class="button-group">
            <el-button type="primary" @click="onCommit">确定</el-button>
            <el-button @click="onCancle">取 消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { ARTICLE_OPS_TYPE } from '@/constant/article'
import { getArticleDetailApi, postArticleApi, putArticleApi } from '@/api/article'
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
const props = defineProps({
    opsType: {
        type: String,
        required: true,
    },
    articleId: {
        type: String,
        default: '',
    },
});
const emit = defineEmits(['finish', 'close']);

// 文章对象
const article = reactive({
    id: '',
    stem: '',
    content: '',
});


const editorKey = ref(0);


getArticleDetail();
async function getArticleDetail() {
    if (!props.articleId) return;

    const data = await getArticleDetailApi(props.articleId);

    Object.keys(article).forEach(key => {
        article[key] = data[key];
    });
}

const onCommit = async () => {
    if (props.opsType === ARTICLE_OPS_TYPE.ADD) {
        console.log('新增文章');
        await postArticleApi(article);

        // 清空表单
        Object.keys(article).forEach((key) => {
            article[key] = ''
        })

        // 强制更新 QuillEditor
        editorKey.value += 1;
    } else {
        console.log('编辑文章');

        await putArticleApi(article);

        // 强制更新 QuillEditor
        editorKey.value += 1;
    }
    // 成功提示
    ElMessage.success(props.opsType === ARTICLE_OPS_TYPE.ADD ? '新增成功' : '编辑成功');
    // 通知父组件关闭抽屉 (1. 关闭抽屉 2. 刷新列表)
    emit('finish');
};

const onCancle = () => {
    emit('close');
}

const onRefresh = () => {
    editorKey.value += 1;
    getArticleDetail();
}

</script>

<style scoped lang="scss">
.el-form {
    .el-input {
        height: 50px;
    }

    // 样式穿透
    :deep(.ql-container) {
        width: 100%;
        min-height: 200px;
    }

    .button-group {
        margin-top: 150px;
        /* 调整这个值来控制按钮组的垂直间距 */
    }
}
</style>